package com.byton.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.byton.order.bean.Order;
import com.byton.order.properies.OrderProperties;
import com.byton.order.service.OrderService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Description:
 *
 * @Author byteon (liyong98k@163.com)
 * @Create 2025-04-02 15:31
 */
//@RefreshScope // 支持动态刷新
//@RequestMapping("/api/order")
@RestController
@Slf4j
public class OrderController {

    @Autowired
    OrderService orderService;

//    @Value("${order.timeout}")
//    String orderTimeout;
//    @Value("${order.auto-confirm}")
//    String orderAutoConfirm;

    @Autowired
    OrderProperties orderProperties;
    @GetMapping("/config")
    public String config(){
        return "order.timeout="+orderProperties.getTimeout()+"; " +
                "order.auto-confirm="+orderProperties.getAutoConfirm() + "; "+
                "order.db-url="+orderProperties.getDbUrl();
    }

    @GetMapping("/create")
    public Order createOrder(@RequestParam("productId") Long productId, @RequestParam("userId") Long userId){
        return orderService.createOrder(productId, userId);
    }

    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order", fallback = "seckillFallback")
    public Order seckill(@RequestParam(value = "productId", required = false) Long productId,
                         @RequestParam(value = "userId", defaultValue = "888") Long userId){
        Order order = orderService.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }

    public Order seckillFallback(Long productId, Long userId, Throwable exception){
        System.out.println("seckillFallback .......");
        Order order = new Order();
        order.setId(productId);
        order.setUserId(userId);
        order.setAddress("异常信息：" + exception.getClass());
        return order;
    }

    @GetMapping("/writeDB")
    public String writeDB(){
        log.info("writeDB.......");
        return "writeDB success ........";
    }

    @GetMapping("/readDB")
    public String readDB(){
        log.info("readDB.......");
        return "readDB success ........";
    }
}
